package org.grill.clovercash;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IViewPart;
import org.grill.clovercash.accounts.Account;
import org.grill.clovercash.accounts.Account.Type;

public class AddAccountAction extends Action  {

	public static final String ID = "org.grill.clovercash.accountlistview.actions.add.account";
	
	private AccountListView view;
	
	public AddAccountAction(AccountListView view) {
		this.view = view;
		setText("Add New Account");
		setToolTipText("Add New Account");
		setId(ID);
		setImageDescriptor(CloverCashUIPlugin.getImageDescriptor("new.gif"));
	}
	
	public void init(IViewPart view) {
		
	}

	public void run() {
		Account receiver;
		IStructuredSelection selection = (IStructuredSelection) view.getViewer().getSelection();
		if (selection.isEmpty())
			receiver = CloverCashUIPlugin.getDefault().getRootAccount();
		else {
			receiver = (Account) selection.getFirstElement();
		}
		Account account = createAccount(receiver);
		if (account != null) {
			view.getViewer().expandToLevel(account, 2);

			System.out.println("Added account");
		}
	}

	private Account createAccount(Account receiver) {
		AccountEditDialog dlg = new AccountEditDialog(view.getSite().getShell());
		if (dlg.open() != IDialogConstants.OK_ID)
			return null;
		
		String description = dlg.getDescription();
		Type type = dlg.getType();
		Account account = new Account(dlg.getName(), description, type, receiver);
		
		
		return account;
	}
}
